# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Loss functions
"""

import torch
import torch.nn as nn

from utils.metrics import bbox_iou
from utils.torch_utils import de_parallel


def smooth_BCE(eps=0.1):  # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
    # return positive, negative label smoothing BCE targets
    return 1.0 - 0.5 * eps, 0.5 * eps


class BCEBlurWithLogitsLoss(nn.Module):
    # BCEwithLogitLoss() with reduced missing label effects.
    def __init__(self, alpha=0.05):
        super().__init__()
        self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none')  # must be nn.BCEWithLogitsLoss()
        self.alpha = alpha

    def forward(self, pred, true):
        loss = self.loss_fcn(pred, true)
        pred = torch.sigmoid(pred)  # prob from logits
        dx = pred - true  # reduce only missing label effects
        # dx = (pred - true).abs()  # reduce missing label and false label effects
        alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
        loss *= alpha_factor
        return loss.mean()


class FocalLoss(nn.Module):
    # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
    def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):    # Focal Loss 聚焦损失 loss_fcn:nn.BCEWithLogitsLoss 代价函数 gamma:正样本的幂补偿 alpha:正样本的缩放因子
        super().__init__()
        self.loss_fcn = loss_fcn  # must be nn.BCEWithLogitsLoss()    self.loss_fcn:代价函数
        self.gamma = gamma    # gamma:float gamma
        self.alpha = alpha    # self.alpha:float alpha
        self.reduction = loss_fcn.reduction    # self.reduction:str 指定用于输出的 reduction
        self.loss_fcn.reduction = 'none'  # required to apply FL to each element    设置原本 loss_fcn.reduction 为 'none'

    def forward(self, pred, true):
        loss = self.loss_fcn(pred, true)    # loss:float    计算普通的二分类交叉熵
        # p_t = torch.exp(-loss)
        # loss *= self.alpha * (1.000001 - p_t) ** self.gamma  # non-zero power for gradient stability

        # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
        pred_prob = torch.sigmoid(pred)  # prob from logits    
        p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
        alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
        modulating_factor = (1.0 - p_t) ** self.gamma
        loss *= alpha_factor * modulating_factor

        if self.reduction == 'mean':
            return loss.mean()
        elif self.reduction == 'sum':
            return loss.sum()
        else:  # 'none'
            return loss


class QFocalLoss(nn.Module):
    # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
    def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
        super().__init__()
        self.loss_fcn = loss_fcn  # must be nn.BCEWithLogitsLoss()
        self.gamma = gamma
        self.alpha = alpha
        self.reduction = loss_fcn.reduction
        self.loss_fcn.reduction = 'none'  # required to apply FL to each element

    def forward(self, pred, true):
        loss = self.loss_fcn(pred, true)

        pred_prob = torch.sigmoid(pred)  # prob from logits
        alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
        modulating_factor = torch.abs(true - pred_prob) ** self.gamma
        loss *= alpha_factor * modulating_factor

        if self.reduction == 'mean':
            return loss.mean()
        elif self.reduction == 'sum':
            return loss.sum()
        else:  # 'none'
            return loss


class ComputeLoss:
    # Compute losses
    def __init__(self, model, autobalance=False):
        self.sort_obj_iou = False
        device = next(model.parameters()).device  # get model device
        h = model.hyp  # hyperparameters

        # Define criteria    BCELoss 交叉熵损失
        BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))    # BCEcls:nn.BCEWithLogitsLoss 分类损失函数
        BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))    # BCEobj:nn.BCEWithLogitsLoss 置信度损失函数

        # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3    标签平滑
        self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0))  # positive, negative BCE targets    根据超参数中的变脸计算标签平滑系数, self.cp:正样本的系数 self.cn:负样本的系数

        # Focal loss  
        g = h['fl_gamma']  # focal loss gamma
        if g > 0:
            BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)    # 如果超参数中的 fl_gamma > 0，就计算 FocalLoss

        det = de_parallel(model).model[-1]  # Detect() module
        self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, 0.02])  # P3-P7
        self.ssi = list(det.stride).index(16) if autobalance else 0  # stride 16 index
        # self.BCEcls:分类损失代价函数
        # self.BCEobj:置信度损失代价函数
        # self.gr:1.0
        # self.hyp:dict 超参数
        # self.autobalance False
        self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance
        for k in 'na', 'nc', 'nl', 'anchors':
            setattr(self, k, getattr(det, k))

    def __call__(self, p, targets):  # predictions, targets, model
        device = targets.device
        lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)    # lcls:tensor 分类损失 lbox:tensor box 损失 lobj:置信度损失
        tcls, tbox, indices, anchors = self.build_targets(p, targets)  # targets
        # tcls:[3个tensor] 3 个输出层的 target_class，每个对象的shape为[k]
        # tbox:[3个tensor] 3 个输出层的 target_box，每个对象的shape为[k*4] 其中4为 [box内相对归一化x，y，相对box的w，h]
        # indices:[3个tuple] 其中每个 tuple的size为4，内部为[tensor[k]:全0，tensor[k]:每个target对应的anchor_index, tensor[k]:每个taregt的x方向box_index, tensor[k]:每个target的y方向box_index]
        # anch:[3个tensor] 3 个输出层的相对 target，每个对象的shape为[k*2] 的预置 anchor 大小

        # Losses
        for i, pi in enumerate(p):  # layer index, layer predictions
            # pi:tensor(2*3*80*80*85)    batch_size*anchor_number*grid_x*grid_y*output
            b, a, gj, gi = indices[i]  # image, anchor, gridy, gridx
            tobj = torch.zeros_like(pi[..., 0], device=device)  # target obj    tobj:[2*3*80*80]

            n = b.shape[0]  # number of targets    n:int本次预测的实际标签
            if n:    # 如果有标签
                ps = pi[b, a, gj, gi]  # prediction subset corresponding to targets    ps:tensor[k*85] 实际上和taregt标签对应的预测框数据

                # Regression    回归损失
                pxy = ps[:, :2].sigmoid() * 2 - 0.5    # 不理解为什么这么算看到 detect 中还原坐标的时候有相同的写法，暂时认为是由于训练的时候这样导致的把    pxy:tensor[k*2] 和标签匹配的预测中心
                pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]    # pwh:tensor[k*2] 和标签匹配的anchor宽高
                pbox = torch.cat((pxy, pwh), 1)  # predicted box    pbox:tensor[k*4] xywh
                iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True)  # iou(prediction, target)    iou:ciou,tensor[k]
                lbox += (1.0 - iou).mean()  # iou loss    lbox+=每个预测层的平均值

                # Objectness    置信度损失
                score_iou = iou.detach().clamp(0).type(tobj.dtype)    # source_iou CIOU 截断小于0的数值    tensor.detach()原有张量的拷贝，并从原始的计算图中脱离出来
                if self.sort_obj_iou:
                    sort_id = torch.argsort(score_iou)
                    b, a, gj, gi, score_iou = b[sort_id], a[sort_id], gj[sort_id], gi[sort_id], score_iou[sort_id]
                tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * score_iou  # iou ratio     # tobj中标签有的位置复制为刚刚计算的iou  target_obj中的值为刚刚计算的 iou

                # Classification    分类损失
                if self.nc > 1:  # cls loss (only if multiple classes)
                    t = torch.full_like(ps[:, 5:], self.cn, device=device)  # targets
                    t[range(n), tcls[i]] = self.cp
                    lcls += self.BCEcls(ps[:, 5:], t)  # BCE

                # Append targets to text file
                # with open('targets.txt', 'a') as file:
                #     [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]

            obji = self.BCEobj(pi[..., 4], tobj)
            lobj += obji * self.balance[i]  # obj loss
            if self.autobalance:
                self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()

        if self.autobalance:
            self.balance = [x / self.balance[self.ssi] for x in self.balance]
        lbox *= self.hyp['box']    #lbox:tensor[1]
        lobj *= self.hyp['obj']
        lcls *= self.hyp['cls']
        bs = tobj.shape[0]  # batch size

        return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach()

    def build_targets(self, p, targets):
        # Build targets for compute_loss(), input targets(image,class,x,y,w,h)    p:list[tensor(batch_size*channel*80*80*85|25)]    taregt:tensor(n*6)
        na, nt = self.na, targets.shape[0]  # number of anchors, targets    na:int anchors的数量 3     nt:int 这一 batch_size 预测数据中有 实际有多少个 target
        tcls, tbox, indices, anch = [], [], [], []    # tcls:list target_类别 tbox:list target_box indices:list TODO ?
        gain = torch.ones(7, device=targets.device)  # normalized to gridspace gain    # gain:tensor(7) 归一化为网格空间增益
        a_ = torch.arange(na, device=targets.device)    # 3
        aa_ = a_.float()
        aaa_ = aa_.view(na, 1)    # 3*1
        aaaa_ = aaa_.repeat(1, nt, 2)    # torch.tensor.repeat(*size) 沿着每一个维度
        ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt)  # same as .repeat_interleave(nt)    ai:tensor[3*n] 每个anchor的每个target[[0000000],[11111],[2222222]]
    
        targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2)  # append anchor indices    target:[3*n*7] 最后一个是 (0, c,x,y,w,h,anchor_index) targets 重复3次是让每个box的anchor都有相同的targets  每个 anchor的每个target的每个target信息
        # print(targets[0][0])

        g = 0.5  # bias
        off = torch.tensor([[0, 0],
                            [1, 0], [0, 1], [-1, 0], [0, -1],  # j,k,l,m
                            # [1, 1], [1, -1], [-1, 1], [-1, -1],  # jk,jm,lk,lm
                            ], device=targets.device).float() * g  # offsets 不太清楚 off 是做什么的   5*2

        for i in range(self.nl):    # 对于每一个输出层
            # anchors = self.anchors[i]    # 原来的报错 result type Float can't be cast to the desired output type long int
            anchors, shape = self.anchors[i], p[i].shape    # 修改的    anchors:[[w,h],[w,h],[w,h]] 当前层的 anchors 信息  shape:tensor[2,3,80,80,85]
            gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]]  # xyxy gain    gain:[7] gain[2]=80 gain[3]=80 gain[4]=80 gain[5]=80 gain=[1,1,80,80,80,80,1]

            # Match targets to anchors    匹配 target 到 anchors 中 >>>>>>>>>
            t = targets * gain    # t:[3*n*7] 最后的 7 相当于 xywh 都乘了 80
            if nt:    # 如果有标签
                # Matches    剔除真是标签中过于瘦长的    由于每个输出层的预置 anchor 不一样，可能过滤出来的信息不同
                a_ = t[:, :, 4:6]
                b_ = anchors[:, None]
                r = t[:, :, 4:6] / anchors[:, None]  # wh ratio    r:tensor[3*n*2] 每个anchor每个target的宽和高与预置anchor的宽和高比值
                a_ = torch.max(r, 1 / r)    # a_:tensor[3*n*2] 宽和高的r和1/r中较大的值 最后的2 0:宽比例中较大的r与1/r的对比值 1:高比例中较大的 r与1/r
                aa_ = a_.max(2)    # aa_:max对象
                aaa_ = aa_[0]    # aaa_:tensor[3*n] 其中 n 为每个target的高宽r 1/r 4值中的最大值
                j = torch.max(r, 1 / r).max(2)[0] < self.hyp['anchor_t']  # compare    
                # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t']  # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
                t = t[j]  # filter    # t:tensor[m*7] m<=n 经过 targets 的标签宽高与预置anchor宽高对比过滤掉的 target

                # Offsets    # offset    添加真实标签中的临近 box
                gxy = t[:, 2:4]  # grid xy    gxy:tensor[m,2] 最后的2为每个 target 的标签中心点
                gxi = gain[[2, 3]] - gxy  # inverse    gxi:tensor[m,2] 整个 box 的宽高减去中心点的 xy, 目的是为了计算 中心点在其 box 中的偏移
                j, k = ((gxy % 1 < g) & (gxy > 1)).T    # j:tensor[m] 每个目标中心左边的点是否包括 k:上边
                l, m = ((gxi % 1 < g) & (gxi > 1)).T
                j = torch.stack((torch.ones_like(j), j, k, l, m))    # j:tensor[5*m] 5 为 [1.左边使能,上边使能,右边使能,下边使能]
                a_ = t.repeat((5, 1, 1))    # t:[]    为什么要重复 5 次 TODO
                t = t.repeat((5, 1, 1))[j]     # 没看懂
                a_ = torch.zeros_like(gxy)[None]    # 1*m*2
                b_ = off[:, None]    # 5*1*2
                offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
            else:
                t = targets[0]
                offsets = 0

            # Define
            b, c = t[:, :2].long().T  # image, class b:[m] 真实标签置信度在检测层[i]中经过过滤的结果 c:[m] 真实标签置信度在检测层[i]中经过过滤的结果
            gxy = t[:, 2:4]  # grid xy gxy:[m*2] 真实标签中心点在检测层[i]中经过过滤的结果
            gwh = t[:, 4:6]  # grid wh    gwh:[m*2] 真实标签宽高在检测层[i]中经过过滤的结果
            gij = (gxy - offsets).long()    # gij:[m*2]
            gi, gj = gij.T  # grid xy indices    gi:[m] x方向索引 gj:[m] y方向索引

            # Append
            a = t[:, 6].long()  # anchor indices    a:[m] anchor索引
            # indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1)))  # image, anchor, grid indices    原来的会报错
            indices.append((b, a, gj.clamp_(0, shape[2] - 1), gi.clamp_(0, shape[3] - 1)))    # 修改后的  indeces 中添加了一个tuple(tensor[全0],tensor[重复5遍的anchor_index],tensor[中心x在的box],tensor[中心y在的box])
            tbox.append(torch.cat((gxy - gij, gwh), 1))  # box    tbox 中添加了一个 tensor[k*4](k<=5*m)    其中4是[box内归一化x,box内归一化y,box相对w,box相对h]
            anch.append(anchors[a])  # anchors   anch 中添加了一个 tensor[k*2] 其中2是[预置 anchor_x 预置 anchor_y]
            tcls.append(c)  # class    tcls 添加了一个 tensor[k] 为类别

        return tcls, tbox, indices, anch
        # tcls:[3个tensor] 3 个输出层的 target_class，每个对象的shape为[k]
        # tbox:[3个tensor] 3 个输出层的 target_box，每个对象的shape为[k*4] 其中4为 [box内相对归一化x，y，相对box的w，h]
        # indices:[3个tuple] 其中每个 tuple的size为4，内部为[tensor[k]:全0，tensor[k]:每个target对应的anchor_index, tensor[k]:每个taregt的x方向box_index, tensor[k]:每个target的y方向box_index]
        # anch:[3个tensor] 3 个输出层的相对 target，每个对象的shape为[k*2] 的预置 anchor 大小
